package com.tecklab.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tecklab.demo.common.PageData;
import com.tecklab.demo.common.Result;
import com.tecklab.demo.entity.OperationLogEntity;
import com.tecklab.demo.mapper.OperationLogMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 操作日志控制器
 */
@RestController
@RequestMapping("/api/log")
public class LogController {

    @Autowired
    private OperationLogMapper operationLogMapper;

    private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    /**
     * 分页查询操作日志
     */
    @GetMapping("/page")
    public Result getLogPage(
            @RequestParam("page") Integer pageNum,
            @RequestParam Integer size,
            @RequestParam(required = false) String operation,
            @RequestParam(required = false) String operationType,
            @RequestParam(required = false) String operatorName,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {

        // 创建分页对象
        Page<OperationLogEntity> page = new Page<>(pageNum, size);

        // 构建查询条件
        QueryWrapper<OperationLogEntity> queryWrapper = new QueryWrapper<>();

        if (StringUtils.isNotBlank(operation)) {
            queryWrapper.like("operation", operation);
        }
        if (StringUtils.isNotBlank(operationType)) {
            queryWrapper.eq("operation_type", operationType);
        }
        if (StringUtils.isNotBlank(operatorName)) {
            queryWrapper.like("operator_name", operatorName);
        }
        queryWrapper.ge(StringUtils.isNotBlank(startTime), "created_at", startTime);
        if (StringUtils.isNotBlank(endTime)) {
            LocalDate date = LocalDate.parse(endTime, formatter);
            LocalDate newDate = date.plusDays(1);
            String newEndTime = newDate.format(formatter);
            queryWrapper.lt("created_at", newEndTime);
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc("created_at");

        // 执行分页查询
        page = operationLogMapper.selectPage(page, queryWrapper);

        return Result.success(new PageData<>(page.getRecords(), page.getTotal()));
    }

    /**
     * 获取所有操作日志 ,Map<String, Object> getLogList()  ,
     * Map<String, Object> result = new HashMap<>();
     */
    @GetMapping("/list")
    public Result<List<OperationLogEntity>> getLogList() {
        Result<List<OperationLogEntity>> result = new Result<>();

        QueryWrapper<OperationLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("created_at");

        List<OperationLogEntity> logs = operationLogMapper.selectList(queryWrapper);

        result.setCode(200);
        result.setMessage("查询成功");
        result.setData(logs);

        return result;
    }

    /**
     * 删除操作日志
     */
    @DeleteMapping("/{id}")
    public Result deleteLog(@PathVariable Integer id) {
        Result result = new Result<>();

        // 检查日志是否存在
        OperationLogEntity existingLog = operationLogMapper.selectById(id);
        if (existingLog == null) {
            result.setCode(404);
            result.setMessage("日志不存在");
            return result;
        }

        int rows = operationLogMapper.deleteById(id);

        if (rows > 0) {
            result.setCode(200);
            result.setMessage("删除成功");
        } else {
            result.setCode(500);
            result.setMessage("删除失败");
        }


        return result;
    }

    /**
     * 批量删除操作日志
     */
    @DeleteMapping("/batch")
    public Result batchDeleteLogs(@RequestBody List<Integer> ids) {
        Result result = new Result();

        if (ids == null || ids.isEmpty()) {
            result.setCode(400);
            result.setMessage("请选择要删除的日志");
            return result;
        }

        int rows = operationLogMapper.deleteBatchIds(ids);

        if (rows > 0) {
            result.setCode(200);
            result.setMessage("批量删除成功，共删除" + rows + "条记录");
        } else {
            result.setCode(500);
            result.setMessage("批量删除失败");
        }


        return result;
    }

    /**
     * 获取操作类型统计
     */
    @GetMapping("/statistics")
    public Result getLogStatistics() {
        Result result = new Result<>();

        // 总日志数
        Long totalCount = operationLogMapper.selectCount(null);

        // 按操作类型统计
        QueryWrapper<OperationLogEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("operation_type", "COUNT(*) as count")
                .groupBy("operation_type");

        List<Map<String, Object>> typeStats = operationLogMapper.selectMaps(queryWrapper);

        result.setCode(200);
        result.setMessage("统计成功");
        //Map<String, Object> data = new HashMap<>();
        Result data = new Result<>();
        data.setData(totalCount);
        data.setData(typeStats);
        //data.put("typeStatistics", typeStats);
        result.setData(data);

        return result;
    }
}
